package com.gitee.itembucket

import com.gitee.itembucket.core.bucket.ItemOperationLog
import com.gitee.itembucket.core.storage.Storage
import org.bukkit.Bukkit
import taboolib.common.io.newFile
import taboolib.common.platform.ProxyCommandSender
import taboolib.common.platform.command.CommandBody
import taboolib.common.platform.command.CommandHeader
import taboolib.common.platform.command.mainCommand
import taboolib.common.platform.command.subCommand
import taboolib.common.platform.function.getDataFolder
import taboolib.expansion.createHelper
import java.io.File
import java.text.SimpleDateFormat

@CommandHeader("itembucketlog", aliases = ["ibucketlog","ilog","ibl"])
object ItemBucketLogCommand {

    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

    @CommandBody
    val main = mainCommand {
        createHelper()
    }

    @CommandBody
    val pull = subCommand {
        dynamic("player") {
            suggestion<ProxyCommandSender>{ _, _ -> Bukkit.getOfflinePlayers().map { it.name!! } }

            execute<ProxyCommandSender>{ _, _, argument ->
                val offlinePlayer = Bukkit.getOfflinePlayer(argument)
                if (offlinePlayer.name != null) {
                    val logs = Storage.INSTANCE.getItemLogs(offlinePlayer)
                    newFile(File(getDataFolder(),"log/${offlinePlayer.player?.displayName ?: offlinePlayer.uniqueId}.txt")).writeText(createText(logs))
                }
            }

        }
    }

    private fun createText(logs: List<ItemOperationLog>): String {
        val builder = StringBuilder()
        logs.forEach {
            builder.append("${dateFormat.format(it.createTime)} 类型: ${it.type} 玩家: ${Bukkit.getOfflinePlayer(it.user).player?.displayName ?: "未知"} 库所属: ${Bukkit.getOfflinePlayer(it.operator).player?.displayName ?: "未知"} 物品: ${it.itemId}*${it.amount}\n")
        }
        return builder.toString()
    }

}